// pages/address-add/address-add.js
const apiurl = require('../../config').apiurl;
import {
  Pulibc
} from '../../models/public.js'
const pulibc = new Pulibc();
// 城市组件
const defaultOptions = {
  method: 'GET'
};

function fetch(url) {
  let options = {};
  options.url = url;
  return new Promise((resolve, reject) => {
    options.success = resolve;
    options.fail = reject;
    wx.request({
      ...defaultOptions,
      ...options
    });
  });
}
const API = 'https://www.kenlimi.com.cn/public/wxapi/area/area_list&area_id='

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address_id: 0,
    member_id: 0,
    true_name: '',
    mob_phone: '',
    chain_provinceid: 0,
    chain_cityid: 0,
    chain_areaid: 0,
    area_info: '',
    address: '',
    is_default: 0,
    // 城市组件初始化数据
    multiIndex: [0, 0, 0],
    objectCityArray: [],
    provinceData: [],
    cityData: [],
    districtData: [],
    isClicked: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    if (options.changeBool) {
      wx.setStorageSync('changeBool', options.changeBool);
    }

    // 初始化时清除缓存城市
    if (wx.getStorageSync('selected_add')) {
      wx.removeStorageSync('selected_add');
    }
    this.initCityList();

  },
  // 取消操作
  bindCityCancel() {
    const data = wx.getStorageSync('selected_add');
    this.setData({
      'areaPicker.address': data.address,
      'areaPicker.selected': data.selected
    })
  },
  // 确定
  bindMultiPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let value = e.detail.value;
    this.setData({
      multiIndex: e.detail.value
    })
    let cv0 = value[0];
    let cv1 = value[1];
    let cv2 = value[2];
    let provinceData = this.data.provinceData;
    let cityData = this.data.cityData;
    let districtData = this.data.districtData;
    let address, selected;
    if (districtData && districtData.length > 0) {
      address = provinceData[cv0].name + ' ' + cityData[cv1].name + ' ' + districtData[cv2].name;
      selected = [provinceData[cv0], cityData[cv1], districtData[cv2]];
    } else {
      address = provinceData[cv0].name + ' ' + cityData[cv1].name;
      selected = [provinceData[cv0], cityData[cv1]];
    }
    this.setData({
      'areaPicker.address': address,
      'areaPicker.selected': selected,
    })
    console.log("selected", this.data.areaPicker.selected)
    const data = {};
    data.address = address;
    data.selected = selected;
    wx.setStorageSync('selected_add', data);
    this.setData({
      isClicked: true
    })
  },
  // 列滑动
  bindMultiPickerColumnChange: function(e) {
    let self = this;
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      objectCityArray: this.data.objectCityArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value; //每一列对应的值
    let col = e.detail.column;
    if (col == 0) {
      // 滑动省份
      data.multiIndex[1] = 0;
      data.multiIndex[2] = 0;
      fetch(API + self.data.provinceData[data.multiIndex[0]].district_id).then((city) => {
        const cityData = city.data.datas.area_list;
        if (cityData && cityData.length) {
          const dataWithDot = city.data.datas.area_list;
          this.setData({
            cityData: dataWithDot,
            objectCityArray: [self.data.provinceData, cityData, self.data.districtData]
          });
          return fetch(API + dataWithDot[0].district_id);
        } else {
          this.setData({
            cityData: [],
            districtData: [],
          });
        }
      }).then((district) => {
        const districtData = district.data.datas.area_list;
        if (districtData && districtData.length > 0) {
          const dataWithDot = districtData;
          this.setData({
            districtData: dataWithDot,
            objectCityArray: [self.data.provinceData, self.data.cityData, districtData]
          });
        } else {
          this.setData({
            districtData: [],
            objectCityArray: [self.data.provinceData, self.data.cityData, []]
          });
        }
      }).catch((e) => {
        console.error(e);
      });
    } else if (col == 1) {
      // 滑动城市
      data.multiIndex[2] = 0;
      fetch(API + self.data.cityData[data.multiIndex[1]].district_id).then((district) => {
        if (!district) return;
        const districtData = district.data.datas.area_list;
        if (districtData && districtData.length > 0) {
          const dataWithDot = districtData;
          this.setData({
            districtData: dataWithDot,
            objectCityArray: [self.data.provinceData, self.data.cityData, districtData]
          });
        } else {
          this.setData({
            districtData: [],
            objectCityArray: [self.data.provinceData, self.data.cityData, []]
          });
        }
      }).catch((e) => {
        console.error(e);
      });
    }
    console.log("CityArray", self.data.objectCityArray)
  },
  // 初始化城市列表
  initCityList() {
    let self = this;
    fetch(API + '0').then((province) => {
      console.log("province", province)
      const firstProvince = province.data.datas.area_list[0];
      const dataWithDot = province.data.datas.area_list;
      // console.log("dataWithDot", dataWithDot)
      /**
       * 默认选择获取的省份第一个省份数据
       */
      self.setData({
        provinceData: dataWithDot,
      });
      return fetch(API + firstProvince.district_id);
    }).then((city) => {
      const firstCity = city.data.datas.area_list[0];
      const dataWithDot = city.data.datas.area_list;
      self.setData({
        cityData: dataWithDot,
      });
      //地区为空
      self.setData({
        objectCityArray: [this.data.provinceData, this.data.cityData, []]
      })
      return fetch(API + firstCity.district_id);
    }).then((district) => {
      if (!district || district.data.datas.area_list.length == 0) return;
      const firstDistrict = district.data.datas.area_list[0];
      const dataWithDot = district.data.datas.area_list;
      self.setData({
        districtData: dataWithDot,
      });
      console.log("provinceData1", this.data.provinceData)
      // 初始化城市数据，默认选中第一个
      let cityArray = [];
      cityArray = [this.data.provinceData, this.data.cityData, this.data.districtData];
      self.setData({
        objectCityArray: cityArray
      })
      console.log("initCityArray", self.data.objectCityArray)

    }).catch((e) => {
      console.error(e);
    });

  },
  // 切换默认地址
  switch1Change(e) {
    console.log(e.detail.value)
    let checked = e.detail.value;
    if (checked) {
      this.setData({
        is_default: 1
      })
    } else {
      this.setData({
        is_default: 0
      })
    }
    console.log('is_defalut', this.data.is_default);
  },
  // 新增地址
  formSubmit(e) {
    // 提交前校验
    // 手机号和固定号码正则校验
    let phoneReg = /^1[34578]\d{9}$/;
    let telReg = /^0\d{2,3}-?\d{7,8}$/
    if (this.data.true_name == '') {
      pulibc.showToast('请填写会员姓名', 'none');
      return false;
    }
    if (this.data.mob_phone == '') {
      pulibc.showToast('请填写手机电话', 'none');
      return false;
    } else if (!phoneReg.test(this.data.mob_phone)) {
      pulibc.showToast('联系电话格式错误', 'none');
      return false;
    }
    if (!this.data.areaPicker.selected) {
      pulibc.showToast('请填写所在地区', 'none');
      return false;
    }
    if (this.data.address == '') {
      pulibc.showToast('请填写详细地址', 'none');
      return false;
    }
    let url = apiurl + '/address/addres';
    let params = {};
    params.key = wx.getStorageSync('key');
    params.member_id = this.data.member_id;
    params.true_name = this.data.true_name;
    params.mob_phone = this.data.mob_phone;
    params.provincial_id = this.data.areaPicker.selected[0].district_id;
    params.city_id = this.data.areaPicker.selected[1].district_id;
    if (this.data.areaPicker.selected[2]) {
      params.area_id = this.data.areaPicker.selected[2].district_id;
      params.area_info = this.data.areaPicker.selected[0].name + this.data.areaPicker.selected[1].name + this.data.areaPicker.selected[2].name;
    } else {
      params.area_id = 0;
      params.area_info = this.data.areaPicker.selected[0].name + this.data.areaPicker.selected[1].name;
    }
    params.address = this.data.address;
    params.is_default = this.data.is_default;
    wx.request({
      url: url,
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success(res) {
        console.log(res);
        // let msg = res.data.info;
        if (res.data.code == 200) {
          pulibc.showToast('地址添加成功', 'success');
          // pulibc.navigateUrl('../address/address');
          wx.redirectTo({
            url: '../address/address'
          })
        } else if (res.data.datas.error == '请登录') {
          wx.navigateTo({
            url: "../register/register"
          })
        }
        //  else {
        //   pulibc.showToast(msg, 'none');
        // }
      }
    })
  },
  // 获取input的value值
  bindMemberName(e) {
    this.setData({
      true_name: e.detail.value
    })
    // console.log("true_name",this.data.true_name)
  },
  bindPhone(e) {
    this.setData({
      mob_phone: e.detail.value
    })
    // console.log("mob_phone", this.data.mob_phone)
  },
  bindAddress(e) {
    this.setData({
      address: e.detail.value
    })
    // console.log("address", this.data.address)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (wx.getStorageSync("key") == false) {
      wx.navigateTo({
        url: "../register/register"
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})